<?php

namespace App\Console\Commands;

use App\Models\MakeMaster;
use App\Models\ModelMaster;
use App\Models\Warranty;
use App\Models\WarrantySync;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class PushStoreInfo extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:pushStoreData';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     *
     */
    public function handle()
    {
        $syncEntity = WarrantySync::where('system_type',WarrantySync::PUSH_U8)->first();
        if($syncEntity->status == WarrantySync::STATUS_DISABLE){
            exit("该脚本已暂停");
        }
        //开始同步
        WarrantySync::where('system_type',WarrantySync::PUSH_U8)->update(['sync_status'=>WarrantySync::SYNC_STATUS_ING]);

        try{
            $this->pushData();
        }catch (\Exception $e){
            WarrantySync::where('system_type',WarrantySync::PUSH_U8)->update([
                'sync_status'=>WarrantySync::SYNC_STATUS_FAIL,
                'synced_at' => date("Y-m-d H:i:s", time())
            ]);
            exit("异常{$e->getMessage()}");
        }

        //开始同步
        WarrantySync::where('system_type',WarrantySync::PUSH_U8)->update([
            'sync_status'=>WarrantySync::SYNC_STATUS_SUCCESS,
            'synced_at' => date("Y-m-d H:i:s", time())
        ]);

        //return 0;
    }

    public function pushData()
    {
        $page = 1;
        $pageSize = 20;
        while (true) {
            $model = DB::table('users')
                ->leftJoin('store_info', 'users.id', 'store_info.user_id')
                ->leftJoin('dealer', 'users.id', 'dealer.user_id')
                ->leftJoin('cities', 'cities.id', 'users.city')
                ->leftJoin('province_master', 'province_master.id', 'users.province_id');

            $stores = $model
                ->select(
                    'users.company_name',
                    'users.abbr',
                    'users.address',
                    'users.phone_number',
                    'users.first_name',
                    'users.zsdj',
                    'users.mdtype',
                    'cities.simplified_chiness_value as city_name',
                    'province_master.simplified_chiness_value as province_name',
                    'store_info.new_store_code as store_code',
                    'users.status',
                    'users.category_code',
                    'users.category_name'
                )
                ->whereNull('users.deleted_at')
                //->where('status', 1)
                ->where(function ($query){
                    $query->where('users.check_status', 1)->orWhere(function ($query){
                        $query->where('users.check_status', 0)->where('users.user_type', 2);
                    });
                })
                ->where('users.mdtype', '!=', 5)
                ->whereIn('users.user_type', [2, 3])
                ->where('users.creator_id', '!=', 299)
                ->offset(($page - 1) * $pageSize)
                ->limit($pageSize)
                ->orderByRaw(' CONVERT(abbr USING gbk)')
		        ->get();

	    //var_dump($stores);die(0);
            if (count($stores) == 0) {
                dump("数据已查完");
                break;
            }

            $data = [];
            foreach ($stores as $store) {
                if(strpos($store->company_name, 'ASP') === false)
                {
                    $data[] = [
                        'cCusCode' => $store->store_code,
                        'cCusName' => $store->company_name,
                        'cCusAbbName' => $store->abbr,
                        'cCCCode'  => $store->category_code,
                        'CustomerKCode' => $store->mdtype,
                        //'cDCCode'  => $store->province_name . $store->city_name,
                        'cCusPerson' => $store->first_name,
                        'cCusHand'   => $store->phone_number,
                        'status'     =>$store->status,
		            ];

                }
	        }

        if(empty($data))
	    {
	        continue;
	    }	    

        $url = 'http://cbd.etstation.com:8086/Main.asmx/MainForm';
        $client = new Client();
        $result = $client->request('post', $url, [
            'body' => \json_encode([
                'customerModels' => $data
            ], JSON_UNESCAPED_UNICODE),
            'headers' => [
                'Content-type' => 'application/json',
                'Accept'       => 'application/json'
            ]
        ]);
        dump($result->getBody()->getContents());
        $page++;
        }
    }
}
